<template>
  <div class="page-root">
    <BasePanel>
      <a-tabs default-active-key="1" @change="callback">
        <a-tab-pane :tab="item.name" v-for="item in tabs" :key="item.id">
        </a-tab-pane>
      </a-tabs>
      <BaseSearch
        :search="searchProps"
        @searchData="updateTable"
        @resetData="updateTable"
      />
      <div class="table-top-wrap">
        <div class="table-title">
          <!-- <span>列表</span> -->
        </div>
        <!-- <div class="btn-gruop">
          <span>合计消耗：<span style="color: #73ace8; line-height: 35px;">{{ money }}</span></span>
          <a-button type="primary" icon="download" ghost @click="handleExport">导出</a-button>
        </div> -->
      </div>

      <BaseTable
        :loading="loading"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
        :scroll="{ x: 1000 }"
      >
        <template slot="logo" slot-scope="{ record }">
          <div class="table_info">
            <img
              class="table_img"
              :src="
                record.portrait
                  ? processImage(record.portrait)
                  : processImage(
                      '/storage/app_icon/20241115/8db41e60976fb7f1210af4e19c2122cb.png'
                    )
              "
            />
            <div class="table_info_text">
              <div class="table_info_text_title">
                {{ record.customer_name }}
              </div>
              <div class="table_info_good_title">
                快手ID: {{ record.ks_user_id }}
              </div>
            </div>
          </div>
        </template>
        <template slot="performance" slot-scope="{ record }">
          <div class="table_info_text_desc">
            <div>收货人: {{ record.addressee_user }}</div>
            <div>联系电话: {{ record.mobile }}</div>
            <div>收货地址: {{ record.addressee_address }}</div>
            <div>申样数量: {{ record.quantity }}</div>
            <!-- <div style="color: #73ace8;cursor: pointer;" @click="view_details(record.ks_user_id)">查看详情</div> -->
          </div>
        </template>
        <template slot="goods_id" slot-scope="{ record }">
          <div class="table_info">
            <img class="table_img2" :src="processImage(record.image)" />
            <div class="table_info_text">
              <div class="table_info_text_title">{{ record.title }}</div>
              <div class="">
                产品ID:{{ record.goods_id ? record.goods_id : "暂无" }}
              </div>
              <div class="">
                店铺名称:
                {{
                  record.seller_nick_name ? record.seller_nick_name : "暂无店铺"
                }}
              </div>
              <div class="table_info_price">
                <span>¥</span>{{ record.price }}
              </div>
            </div>
          </div>
        </template>
        <template slot="item_price" slot-scope="{ record }">
          <div class="table_info">
            <img class="table_img2" :src="processImage(record.image)" />
            <div class="table_info_text">
              <div style="display: flex; justify-content: space-between">
                <div class="money_l">
                  佣金:{{
                    record.commission_rate
                      ? (record.commission_rate / 10).toFixed(2)
                      : 0
                  }}%
                </div>
                <div class="money_r">
                  服务费:{{
                    record.promotion_rate
                      ? (record.promotion_rate / 10).toFixed(2)
                      : 0
                  }}%
                </div>
              </div>
              <div class="table_info_text_title">{{ record.item_title }}</div>
              <div style="display: flex; justify-content: space-between">
                <div class="">
                  商品ID:{{ record.item_id ? record.item_id : "暂无" }}
                </div>
                <div class="" style="margin-left: 10px">
                  店铺名称:
                  {{
                    record.seller_nick_name
                      ? record.seller_nick_name
                      : "暂无店铺"
                  }}
                </div>
              </div>

              <div class="table_info_price">
                <span>¥</span>{{ record.price }}
              </div>
            </div>
          </div>
        </template>

        <template slot="uuid" slot-scope="{ record }">
          <div class="table_info">
            <div class="table_info_text">
              <div class="">
                申样编号:{{ record.uuid ? record.uuid : "暂无" }}
              </div>
              <div>
                <div class="title_sx" v-if="record.status === 0">
                  创建时间：{{ record.update_time }}
                </div>
                <div
                  class="title_sx"
                  v-if="record.status === 1 && record.is_deliver_goods !== 2"
                >
                  通过时间：{{ record.update_time }}
                </div>
                <div class="title_sx" v-if="record.status === 2">
                  拒绝时间：{{ record.update_time }}
                </div>
                <div class="title_sx" v-if="record.status === 3">
                  发货时间：{{ record.operation_deliver_time }}
                </div>
                <div
                  class="title_sx"
                  v-if="record.status === 4 && record.is_replenish === 0"
                >
                  签收时间：{{ record.receipted_at }}
                </div>
                <div class="title_sx" v-if="record.is_deliver_goods === 2">
                  拒绝发货时间：{{ record.update_time }}
                </div>
                <div class="title_sx" v-if="record.status === 5">
                  取消时间：{{ record.update_time }}
                </div>
                <div class="title_sx" v-if="record.is_replenish === 1">
                  补样时间：{{ record.update_time }}
                </div>
                <div
                  class="scsxs "
                  v-if="
                    (record.status === 0 ||
                      record.status === 4 ||
                      record.status === 5) &&
                    record.is_replenish === 0
                  "
                >
                  申样状态: <span class="color1">{{
                    record.status === 0
                      ? "审核中"
                      : record.status === 1
                      ? "审核通过"
                      : record.status === 2
                      ? "审核拒绝"
                      : record.status === 3
                      ? "已发货"
                      : record.status === 4
                      ? "已签收"
                      : "已取消"
                  }}</span>
                </div>
                <div
                  class="scsxs "
                  v-if="
                    (record.status === 1 || record.status === 3) &&
                    record.is_deliver_goods !== 2
                  "
                >
                  申样状态: <span class="color2">{{
                    record.status === 0
                      ? "审核中"
                      : record.status === 1
                      ? "审核通过"
                      : record.status === 2
                      ? "审核拒绝"
                      : record.status === 3
                      ? "已发货"
                      : "已签收"
                  }}</span>
                </div>
                <div
                  v-if="record.status === 2 && record.is_deliver_goods !== 2"
                  class="scsxs "
                >
                  申样状态: <span class="color3">{{
                    record.status === 0
                      ? "审核中"
                      : record.status === 1
                      ? "审核通过"
                      : record.status === 2
                      ? "审核拒绝"
                      : record.status === 3
                      ? "已发货"
                      : "已签收"
                  }}</span>
                </div>
                <div class="scsxs " v-if="record.is_deliver_goods === 2">
                  申样状态: <span class="color3">拒绝发货</span>
                </div>
                <div class="scsxs " v-if="record.is_replenish === 1">
                  申样状态: <span class="color3">已补样</span>
                </div>
                <div class="View_progress" @click="View_progress(record.uuid)">查看申样进度 ></div>
              </div>
            </div>
          </div>
        </template>

        <template slot="task_status" slot-scope="{ record }">
          <div class="expressage">
            <div>快递公司: <span>{{ record.express_name?record.express_name :'暂无' }}</span></div>
            <div>快递单号: <span>{{ record.express_number?record.express_number :'暂无' }}</span></div>
            <!-- <div>快递状态: <span>{{ record.express_number?record.express_number :'暂未发货' }}</span></div> -->
          </div>
          
        </template>
        <template slot="operate" slot-scope="{ record }">
          <a-popconfirm
            v-if="record.status === 0 || record.status === 1"
            title="取消后无法恢复需重新申样，是否确认取消申样?"
            @confirm="() => onDelete(record.uuid)"
          >
            <a href="javascript:;">取消申样</a>
          </a-popconfirm>
          <div v-if="record.status === 4" ><a href="javascript:;" @click="sample_click(record)">补样</a></div>
          <div v-if="record.status === 1 || record.status === 0" @click="edit_click(record)"><a href="javascript:;">修改收货信息</a></div>
          <div><a href="javascript:;" @click="copy_box(record)">复制推广信息</a></div>
          
        </template>
      </BaseTable>
      <div v-show="dataSource.length > 0" class="page-footer">
        <BasePagination :page-key.sync="pageKey" :get-list="tableInit" />
      </div>
    </BasePanel>
    <FormModal :visible="formShow" :dataObj="defaultObj" @success="successForm" @close="closeForm" />
    <FormModal1 :visible="formShow1" :default="defaultObj1" :task_uuid="task_id" @success="successForm1"  @close="closeForm1" :detailsInfo="detailsInfo" />
    <FormModal2 :visible="formShow2"  @success="successForm2" @close="closeForm2" :promotionId="promotionId" :IdObj="IdObj" />
  </div>
</template>

<script>
import { searchProps2 as searchProps, columns2 as columns } from "./option.js";
import * as Ajax from "@/api/channel";
import { ajaxDownload } from "@/utils/export.js";
import { mapState, mapGetters } from "vuex";
import FormModal from './form';
import FormModal1 from './form1';
import FormModal2 from './form2';
export default {
  components: {FormModal,FormModal1,FormModal2},
  data() {
    return {
      searchProps,
      columns,
      searchForm: {},
      loading: true,
      dataSource: [],
      pageKey: {
        pageSize: 10,
        total: 1,
        current: 1,
      },
      money: 0,
      typeTask_status: {
        1: "进行中",
        2: "已完成",
        0: "未完成",
        "-1": "已失效",
      },
      formShow: false,
      defaultObj: {},
      formShow1: false,
      defaultObj1: [],
      formShow2: false,
      addressList: [],
      promotionId: "",
      tabs: [
        {
          id: 1,
          name: "全部",
          value:''
        },
        {
          id: 2,
          name: "审核中",
          value: 0,
        },
        {
          id: 3,
          name: "审核通过/待发货",
          value: 2,
        },
        {
          id: 4,
          name: "审核拒绝",
          value: 99,
        },
        {
          id: 5,
          name: "拒绝发货",
          value: 3,
        },
        {
          id: 6,
          name: "已发货",
          value: 4,
        },
        {
          id: 7,
          name: "已签收",
          value: 7,
        },
        {
          id: 8,
          name: "已取消",
          value: 5,
        },
        {
          id: 9,
          name: "有补样申请",
          value: 6,
        },
      ],
      send_sample_status:'',
      detailsInfo:{},
      task_id:'',
      IdObj:{},
    };
  },
  created() {
    this.tableInit();
  },
  computed: {
    ...mapGetters("user", ["getCdnUrl", "getUserInfo"]),
  },
  methods: {
    processImage(imageUrl) {
      if (imageUrl === undefined || imageUrl === null) {
        return ""; // 或者返回一个默认的 URL
      }

      if (!imageUrl.startsWith("http")) {
        return this.getCdnUrl + imageUrl;
      }
      return imageUrl;
    },
    callback(key) {
      const item = this.tabs.find(item => item.id == key);
      if (item) {
        this.send_sample_status = item.value;
        this.tableInit();
      }
    },
    sample_click(item){
      this.formShow1 = true;
      this.detailsInfo = item;
    },
    edit_click(item){
      this.formShow2 = true;
      this.IdObj = item;
    },
    getStatusColor(status) {
      const statusColorMap = {
        1: "#1890FF", // 进行中
        2: "#19A452 ", // 已完成
        0: "#E33B35 ", // 未完成
        "-1": "#666666", // 已失效
      };
      return statusColorMap[status] || "#000000"; // 默认颜色为黑色
    },
    async handleExport() {
      this.loading = true;
      const { current, pageSize } = this.pageKey;
      const params = { pageNum: current, pageSize, ...this.searchForm };
      if (params.time) {
        params.startTime = params.time[0] + " 00:00:00";
        params.endTime = params.time[1] + " 23:59:59";
      } else {
        params.startTime = this.getFormattedDate("start");
        params.endTime = this.getFormattedDate("end");
      }
      delete params.time;
      const queryString = new URLSearchParams(params).toString();
      await ajaxDownload(
        `/web/channel/loan/list/export?${queryString}`,
        "get"
      )(params);
      this.loading = false;
    },
    async getSelect() {
      Ajax.getChannelSelect().then((res) => {
        if (res.success) {
          searchProps[0].selectOptions = Array.isArray(res.data)
            ? res.data.map((it) => ({
                ...it,
                label: it.channelName,
                value: it.id,
              }))
            : [];
        }
      });
      Ajax.getProductSelect().then((res) => {
        if (res.success) {
          searchProps[1].selectOptions = Array.isArray(res.data)
            ? res.data.map((it) => ({
                ...it,
                label: `${it.productName}(${it.productNike})`,
                value: it.id,
              }))
            : [];
        }
      });
      const params = { ...this.searchForm };
      if (params.time) {
        params.startTime = params.time[0] + " 00:00:00";
        params.endTime = params.time[1] + " 23:59:59";
      } else {
        params.startTime = this.getFormattedDate("start");
        params.endTime = this.getFormattedDate("end");
      }
      delete params.time;
      const res = await Ajax.loanlistsum(params);
      if (res.success) {
        this.money = res.data;
      }
    },
    updateTable(params = {}) {
      this.searchForm = { ...params };
      this.pageKey = this.$options.data().pageKey;
      this.tableInit();
    },
    // 当天日期
    getFormattedDate(type) {
      const today = new Date();
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, "0");
      const day = String(today.getDate()).padStart(2, "0");

      if (type === "start") {
        return `${year}-${month}-${day} 00:00:00`;
      } else if (type === "end") {
        return `${year}-${month}-${day} 23:59:59`;
      }
    },
    // table 初始化
    tableInit() {
      this.loading = true;
      const { current, pageSize } = this.pageKey;
      const params = {
        page: current,
        list_rows: pageSize,
        send_sample_status: this.send_sample_status,
        ...this.searchForm,
      };
      if (params.time) {
        params.start_time = params.time[0] + " 00:00:00";
        params.end_time = params.time[1] + " 23:59:59";
      }
      delete params.time;
      Ajax.samplesList(params)
        .then((res) => {
          if (res.error === 0) {
            this.dataSource = res.data.data;
            this.pageKey.total = res.data.total;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    showDetails(id) {
      this.$emit("show-details", id);
    },

    view_details(ks_user_id) {
      this.formShow1 = true;
      Ajax.talentDeliveryRateDetail({ ks_user_id }).then((res) => {
        if (res.error === 0) {
          this.defaultObj1 = [res.data];
        }
      });
    },
    View_progress(uuid){
      this.formShow = true;
      Ajax.samplesInfo({ uuid }).then((res) => {
        if (res.error === 0) {
          this.defaultObj = res.data;
        }
      });
    },
    View_address(id) {
      this.formShow2 = true;
      this.promotionId = id;
    },
    successForm() {
      this.formShow = false;
      this.defaultObj = {};
    },
    closeForm() {
      this.formShow = false;
      this.defaultObj = {};
      this.tableInit();
    },
    successForm1() {
      this.formShow1 = false;
      this.defaultObj1 = [];
    },
    closeForm1() {
      this.formShow1 = false;
      this.defaultObj1 = [];
    },
    successForm2() {
      this.formShow2 = false;
      this.addressList = [];
    },
    closeForm2() {
      this.formShow2 = false;
      this.addressList = [];
    },
    onDelete(uuid) {
      Ajax.samplesCancel({ uuid })
        .then((res) => {
          if (res.error === 0) {
            this.$message.success("取消申样成功");
            this.tableInit();
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    async copy_box(item) {
      try {
        await navigator.clipboard.writeText(` 商品ID:${item.item_id ? item.item_id : '暂未绑定商品'}
        商品名称:${item.item_title  ? item.item_title : '暂未绑定商品'}
        快递公司:${item.express_name ? item.express_name : '暂未发货'}
        快递单号:${item.express_number ? item.express_number : '暂未发货'}
        价格:${item.item_price ? item.item_price  / 100 : '暂未绑定商品'}
        佣金:${item.commission_rate ? `${item.commission_rate / 10}%` : '暂未绑定商品'}
        订单备注:${item.remark ? item.remark : '暂未备注'}
        `);
        this.$message.success('复制成功');
      } catch (err) {
        // console.error('复制到剪贴板失败', err);
        this.$message.success('复制失败');
      }
    },
   
  },
};
</script>

<style lang="scss" scoped>
.BasePanel-root {
  padding: 10px 20px 20px;
}

.tabs-wrap {
  margin-bottom: 10px;
}

.table-wrap {
  margin-top: 16px;
}

.table-top-wrap {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.table-title {
  flex: 1;

  span {
    line-height: 32px;
    font-weight: bold;
    font-size: 16px;
    display: flex;
    align-items: center;

    &::before {
      content: "";
      display: block;
      width: 3px;
      height: 18px;
      background-color: #1890ff;
      margin-right: 8px;
      position: relative;
      top: -1px;
    }
  }
}

.btn-gruop {
  display: flex;
  justify-content: flex-end;

  & > button {
    margin-left: 12px;

    &:first-child {
      margin-left: 0;
    }
  }
}
.table_info {
  display: flex;
  align-items: center;
  cursor: pointer;
  .table_img {
    width: 100px;
    height: 100px;
    border-radius: 50%;
  }
  .table_img2 {
    width: 100px;
    height: 100px;
    border-radius: 4px;
  }

  .table_info_text {
    margin-left: 20px;
    font-size: 12px;
    line-height: 26px;
    .table_info_text_title,
    .table_info_good_title {
      width: 260px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .table_info_price {
      font-weight: 600;
      font-size: 16px;
      color: #e33b35;
      span {
        font-size: 12px;
      }
    }
    .money_l {
      height: 19px;
      background: #ffeeee;
      border-radius: 3px;
      padding: 1px 4px;
      font-weight: 400;
      font-size: 12px;
      color: #e33b35;
      text-align: center;
      line-height: 20px;
    }
    .money_r {
      height: 19px;
      background: #fff6ee;
      border-radius: 3px;
      padding: 1px 4px;
      font-weight: 400;
      font-size: 12px;
      color: #ff790c;
      line-height: 20px;
    }
    .View_progress {
      font-weight: 400;
      font-size: 14px;
      color: #1890FF;
    }
  }

  .color1 {
		color: #999999;
	}

	.color2 {
		color: #19a452;
	}

	.color3 {
		color: #e33b35;
	}
}
.expressage {
    span {
      font-size: 12px;
      color: #333333;
    }
  }
</style>
